package Sort;

import java.util.Arrays;

/**
 * @description: 快速排序
 * @author: zhuangxiaoyan
 * @date: 2023/10/12 7:54
 * @param:
 * @return:
 **/
public class 快速排序 {

    public static void quickSort(int[] array) {
        sort(array, 0, array.length - 1);
    }

    private static void sort(int[] array, int left, int right) {
        if (array == null || left >= right || array.length <= 1) {
            return;
        }
        int mid = partition(array, left, right);
        sort(array, left, mid);
        sort(array, mid + 1, right);
    }

    private static int partition(int[] array, int left, int right) {
        // 选择左边的第一个数做中间数
        int temp = array[left];
        while (right > left) {
            // 先从右边开始找到一个比temp小的值
            while (left < right && temp <= array[right]) {
                --right;
            }
            // 当基准数大于了 arr[left]，则填坑
            if (left < right) {
                array[left] = array[right];
                ++left;
            }
            // 先从左边开始找到一个比temp大的值
            while (left < right && temp >= array[left]) {
                ++left;
            }
            if (left < right) {
                array[right] = array[left];
                --right;
            }
        }
        array[left] = temp;
        return left;
    }


    public static void main(String[] args) {
        int[] array = new int[]{6, 1, 2, 7, 9, 3, 4, 5, 8};
        quickSort(array);
        System.out.println(Arrays.toString(array));
    }
}
